/*
 * SerialProtocol.hpp
 *
 *  Created on: Apr 20, 2012
 *      Author: steffen
 */

#ifndef SERIALPROTOCOL_HPP_
#define SERIALPROTOCOL_HPP_

#include <Stream.h>

#include "RS232ProtocolPacket.h"

class SerialProtocol
{
public:
	SerialProtocol(Stream& myStream);
	void Initialize(void);

	CRS232ProtocolPacket* Service(void);

	void SendPacket(CRS232ProtocolPacket* ptrPacketToBeSent);

private:

	typedef enum
	{
		IDLE,
		RECEIVE,
		VERIFY
	} State;

	// The data stream (i.e. the serial port)
	Stream &_mStream;

	// State of the service state machine
	State _mState;

	// Timeout (in ms) for receiving a packet
	unsigned int _mRcvTimoutMs;

	unsigned long _mCounterMsLast;

	CRS232ProtocolPacket _mPacketReceived;

	// Returns true if a certain delay from the last time 'mCounterMsLast'
	// has been set expired, otherwise false. Upon expiration (i.e. return
	// of true) it resets the counter to the current count.
	bool CounterExpired(unsigned long expirationDelayMs);

	// Resets the delay expiration counter
	void CounterReset(unsigned long resetValue = 0);

	// Verifies the received data packet (checksum)
	bool VerifyReceivedPacket(char* ptrRxChars, int iNumberOfRxChars, char cChecksum);

	void SendCharacter(char cCharToBeSent);
};


#endif /* SERIALPROTOCOL_HPP_ */
